import { ImageAsset } from "cc";
import { resources } from "cc";
import { Sprite } from "cc";
import { SpriteFrame } from "cc";
import { Color, Texture2D } from "cc";
import { Res } from "../common/loader/ResLoader";

/****************************************
 * @Date: 2021-08-11 16:41:12
 * @LastEditors: Alonc
 * @LastEditTime: 2022-09-02 14:50:57
 */
export class ImageUtil {
    public static assetToSF(asset: ImageAsset): SpriteFrame {
        const texture = new Texture2D();
        texture.image = asset;
        const spriteFrame = new SpriteFrame();
        spriteFrame.texture = texture;
        return spriteFrame;
    }

    public static loadImgByPath(sprite: Sprite, path: string) {
        resources.load(path, ImageAsset, (err, imageAsset) => {
            if (err) {
                console.error(`加载【${ path }】图标资源不存在`);
                return;
            }
            sprite.spriteFrame = ImageUtil.assetToSF(imageAsset);
        });
    }

    public static async loadSpriteFrameAsync(path: string): Promise<SpriteFrame> {
        const image: ImageAsset = await Res.Loader.loadAsync(path) as ImageAsset;
        return ImageUtil.assetToSF(image);
    }
}
